package com.xcf.controller.business.bookingcargo;

import cn.com.xcf.dao.model.FactBookingCargo;
import cn.com.xcf.dao.model.FactBookingNote;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xcf.controller.base.BaseController;
import com.xcf.controller.base.ExportDataHandler;
import com.xcf.entity.Page;
import com.xcf.service.business.bookingcargo.BookingCarService;
import com.xcf.service.business.bookingcargo.BookingCargoService;
import com.xcf.service.business.bookingcargo.BookingNoteService;
import com.xcf.util.DateUtil;
import com.xcf.util.PageData;
import com.xcf.util.ResponseResult;
import com.xcf.util.ResponseStatusEnum;
import com.xcf.util.SysConstants;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/bookingCargo")
public class BookingCargoController  extends BaseController implements ExportDataHandler{
	protected Logger logger = LoggerFactory.getLogger(BookingCargoController.class);
	@Autowired
	private BookingNoteService bookingNoteService;
	@Autowired
	private BookingCargoService bookingCargoService;
	@Autowired
	private BookingCarService bookcarservice;
	@RequestMapping(value = "/forward")
	public ModelAndView forward(HttpServletRequest request){
		ModelAndView mv =  new ModelAndView();
		Map<String,String[]> map = request.getParameterMap();
		
		PageData pd = new PageData();
		pd = this.getPageData();
		List<PageData> list = bookingCargoService.findByBillCode(pd);
		
		if(list.size()!=0){
			pd = list.get(0);
			mv.addObject("pd", pd);
			//应收费用
			PageData pdCost = bookingCargoService.findTaxByBillCode(pd);
			//应付费用
			PageData pdCostOut = bookingCargoService.findCostOutByBillCode(pd);
			if(pdCost!=null){
				BigDecimal sum_NO_TAX_PRICE = (BigDecimal) pdCost.get("sum_NO_TAX_PRICE");
				BigDecimal sum_tax = (BigDecimal) pdCost.get("sum_tax");
				BigDecimal sum_TAX_PRICE = (BigDecimal) pdCost.get("sum_TAX_PRICE");
				mv.addObject("sum_NO_TAX_PRICE",sum_NO_TAX_PRICE.setScale(2, BigDecimal.ROUND_HALF_UP));
				mv.addObject("sum_tax",sum_tax.setScale(2, BigDecimal.ROUND_HALF_UP));
				mv.addObject("sum_TAX_PRICE", sum_TAX_PRICE.setScale(2, BigDecimal.ROUND_HALF_UP));
				
			}
			if(pdCostOut!=null){
				BigDecimal sum_NO_TAX_PRICE_ = (BigDecimal) pdCostOut.get("sum_NO_TAX_PRICE_");
				BigDecimal sum_tax_ = (BigDecimal) pdCostOut.get("sum_tax_");
				BigDecimal sum_TAX_PRICE_ = (BigDecimal) pdCostOut.get("sum_TAX_PRICE_");
				mv.addObject("sum_NO_TAX_PRICE_",sum_NO_TAX_PRICE_.setScale(2, BigDecimal.ROUND_HALF_UP));
				mv.addObject("sum_tax_",sum_tax_.setScale(2, BigDecimal.ROUND_HALF_UP));
				mv.addObject("sum_TAX_PRICE_",sum_TAX_PRICE_.setScale(2, BigDecimal.ROUND_HALF_UP));
			}
			
			
		}
		
		if(map.containsKey("url") && map.get("url").length > 0){
			mv.setViewName(String.valueOf(map.get("url")[0]));
		}
		for (String key : map.keySet()) {
			String[] val = map.get(key);
			if(null != val && val.length == 1){
				mv.addObject(key, val[0]);
			}else if(null != val && val.length > 1){
				mv.addObject(key, val);
			}
		}
		return mv;
	}


	//点击保存按钮
	@RequestMapping(value="list")
	@ResponseBody
	public ResponseResult list(int page ,int limit ,FactBookingNote bookingNote, String startDate , String endDate){
		limit = limit > 0 ? limit : SysConstants.PAGE_SIZE;
		PageHelper.startPage(page, limit);
		Map params = Maps.newHashMap();
		params.put("startDate" , startDate);
		params.put("endDate" , endDate);
		params.put("ID",bookingNote.getId());
		params.put("box_REQUIREMENT",bookingNote.getBox_REQUIREMENT());
		params.put("billCode" , bookingNote.getBillCode());
		params.put("ladingBillCode" ,bookingNote.getLadingBillCode() );
		params.put("containerOwner" ,bookingNote.getContainerOwner() );
		params.put("businessType" , bookingNote.getBusinessType());
		params.put("riverDelivery" , bookingNote.getRiverDelivery());
		params.put("riverUnload" , bookingNote.getRiverUnload());
		params.put("riverPort" , bookingNote.getRiverPort());
		params.put("forwarderCustomerService" , bookingNote.getForwarderCustomerService());
		params.put("tradeType" , bookingNote.getTradeType());
		List<Map> list = bookingCargoService.queryList(params);
		return ResponseResult.success(new PageInfo(list));
	}
	//修改
@RequestMapping(value="/update")
@ResponseBody
public String update() throws Exception{
PageData pd = new PageData();
pd =this.getPageData();
bookingCargoService.update(pd);
	return null;

	
}
	@RequestMapping(value="queryBookingNote")
	@ResponseBody
	public ResponseResult queryBookingNote(String billCode){
		if(StringUtils.isEmpty(billCode)){
			return ResponseResult.paramError("托单编号为空！");
		}
		FactBookingNote bookingNote = bookingNoteService.queryByBillCode(billCode);
		return ResponseResult.success(bookingNote);
	}

	@RequestMapping(value="queryBookingCargo")
	@ResponseBody
	public ResponseResult queryBookingCargo(String billCode){
		if(StringUtils.isEmpty(billCode)){
			return ResponseResult.paramError("托单编号为空！");
		}
		FactBookingCargo bookingCargo = bookingCargoService.queryByBillCode(billCode);
		return ResponseResult.success(bookingCargo);
	}

	@RequestMapping(value="bookingCargo")
	@ResponseBody
	public Object bookingCargo(FactBookingCargo bookingCargo){
		if(bookingCargo == null){
			return ResponseResult.paramError("订舱信息为空！");
		}
		if(StringUtils.isEmpty(bookingCargo.getBillCode())){
			return ResponseResult.paramError("托单编号为空！");
		}
		boolean result = bookingCargoService.modifyBookingCargo(bookingCargo);
		if(!result){
			result = bookingCargoService.saveBookingCargo(bookingCargo);
		}
		return ResponseResult.success(result);
	}

	@RequestMapping(value="impBookingCargo")
	@ResponseBody
	public Object impBookingCargo(@RequestParam("file") CommonsMultipartFile file) {
		try {
			FactBookingNote bookingNote = readExcel(file);
			if(bookingNote != null && StringUtils.isNotBlank(bookingNote.getBillCode())){
				bookingNote = bookingNoteService.queryByBillCode(bookingNote.getBillCode());
				if(null != bookingNote){
					bookingNote.setIsPutBox(1);
					boolean updateRes = bookingNoteService.updateInfo(bookingNote);
					if(updateRes){
						return ResponseResult.success(bookingNote.getBillCode());
					}
				}
			}
			logger.error("导入放箱操作失败 ， bookingNote：{}" , bookingNote);
		} catch (Exception e) {
			logger.error("读取上传文件失败, " ,e);
		}
		return ResponseResult.fail("上传文件失败");
	}

	private FactBookingNote readExcel(CommonsMultipartFile file) throws Exception {
		InputStream inputXML = new BufferedInputStream(getClass().getResourceAsStream("/template/excel/putbox.xml"));
		XLSReader mainReader = ReaderBuilder.buildFromXML(inputXML);
		InputStream inputXLS = new BufferedInputStream(file.getInputStream());
		Map beans = new HashMap();
		FactBookingNote bookingNote = new FactBookingNote();
		beans.put("bookingNote", bookingNote);
		XLSReadStatus readStatus = mainReader.read( inputXLS, beans);
		if(readStatus.isStatusOK()){
			return bookingNote;
		}
		return null;
	}


	@Override
	public List getData(String type, Map param, Page page) {
		if(MapUtils.isEmpty(param) || param.get("billCode") == null || StringUtils.isBlank(param.get("billCode").toString())){
			return Lists.newArrayList();
		}
		String billCode = param.get("billCode").toString();
		FactBookingNote bookingNote = bookingNoteService.queryByBillCode(billCode);
		if("putbox".equalsIgnoreCase(type)){
			bookingNote.setIsPutBox(1);
		}
		if("bookingcargo-AZ".equalsIgnoreCase(type)){
			bookingNote.setIsBookingCargo(1);
		}
		if("bookingcargo-Ak".equalsIgnoreCase(type)){
			bookingNote.setIsBookingCargo(1);
		}
		 boolean updateRes = bookingNoteService.updateInfo(bookingNote);
		if(updateRes){
			Lists.newArrayList(bookingNote);
		}
		return Lists.newArrayList(bookingNote);
	}

	@Override
	public String getService() {
		return  getClass().getSimpleName();
	}

	@Override
	public Map<String, String> setNames() {
		Map m = new HashMap(3);
		m.put("putbox","putbox.xls");
		m.put("putboxName","放箱通知书("+ DateUtil.getSdfTimes()+").xls");
		m.put("putboxModule",getService());

		m.put("bookingcargo-AK","bookingcargo-AK.xls");
		m.put("bookingcargo-AKName","订舱通知书("+ DateUtil.getSdfTimes()+").xls");
		m.put("bookingcargo-AKModule",getService());

		
		m.put("bookingcargo-AZ","bookingcargo-AZ.xls");
		m.put("bookingcargo-AZName","订舱通知书("+ DateUtil.getSdfTimes()+").xls");
		m.put("bookingcargo-AZModule",getService());
		return m;
	}
}
